package main

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"report/controllers"
	"report/controllers/admin"
	"report/reportdb"
)

func main() {
	router := httprouter.New()
	router.POST("/login", controllers.Login)
	router.GET("/listproducts", BasicAuth(controllers.ListAllProducts))

	//admin router
	router.POST("/admin/user", admin.AddUser)
	router.POST("/admin/product", admin.AddOrUpdateProduct)
	router.GET("/admin/product/:productname", admin.GetProduct)
	router.GET("/admin/product/:productname/del", admin.RemoveProduct)

	fmt.Println("begin to listen...")

	reportDB := reportdb.New()
	reportdb.InitAdminUser()
	defer reportDB.Close()

	err := http.ListenAndServe(":8888", &Server{router})
	if err != nil {
		panic(err)
	}
	fmt.Println("end...")
}

type Server struct {
	r *httprouter.Router
}

func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	// Allow ajax cross domain
	rw.Header().Set("Access-Control-Allow-Origin", "*")
	// Set Max cache age 10min
	rw.Header().Set("Access-Control-Max-Age", fmt.Sprintf("%d", 60*10))

	s.r.ServeHTTP(rw, req)
}

/**
Http Basic Authentication
*/
func BasicAuth(h httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		if username, pwd, ok := r.BasicAuth(); ok {
			if reportdb.Login(username, pwd) == nil {
				h(w, r, ps)
				return
			}
		}
		w.Header().Set("WWW-Authenticate", "Basic realm=\"Please login in\"")
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
	}
}
